#!/usr/bin/env python

import sys
import cgi
import cgitb; cgitb.enable()
import re
import os

import kid
kid.enable_import()

from harava.template import validate

from harava.config import Config, StaticSource, DEFAULT_CONFNAME
from harava.lookup import LookupService
from harava.model import ModelService
from harava.session import Session

CONFDIR = "/etc/harava"
# regexp for determining that a configuration name is safe to use
SAFE_CONFNAME = re.compile(r'^[a-zA-Z0-9-_]+$')

form = cgi.FieldStorage()

confname = form.getfirst("config") or DEFAULT_CONFNAME
if not confname or not SAFE_CONFNAME.match(confname):
  print "Content-type: text/plain"
  print ""
  print "Invalid config name:", confname
  sys.exit(1)

cfg = Config(confname=confname, confdir=CONFDIR)
model = ModelService(cfg)
lookup = LookupService(cfg, model)

if not (form.has_key("url")):
  print "Content-type: text/html"
  print ""
  
  template = validate.Template(baseurl=cfg.getBaseURL())
  template.write(sys.stdout, output='xhtml-strict', format='compact')
  sys.exit(1)

url = form.getfirst("url")
source = form.getfirst("source")
srctype = form.getfirst("type")

src = None
if source and source != 'online':
  for src in cfg.getSources():
    if src.getName() == source:
      break
else:
  src = StaticSource(cfg, 'online', srctype)

if src is None:
  print "Content-type: text/plain"
  print ""
  print "Unknown source name:", source
  print ""
  print "Config name:", cfg.getConfigName() 
  print "Known sources:", ", ".join([src.getName() for src in cfg.getSources()])
  sys.exit(1)

print "Content-type: text/html"
print ""

sess = Session(cfg, lookup, model, src, url=url)
sess.start()
sess.close()
